package cn.ecut.servlet;

import cn.ecut.model.User;
import cn.ecut.services.Userservices;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
@WebServlet("user/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id=req.getParameter("id");
        String name=req.getParameter("name");
        String sex=req.getParameter("sex");
        String password=req.getParameter("password");
        String configpassword=req.getParameter("configpassword");
        String tel=req.getParameter("tel");

        String msg="";
        User user=new User();
        user.setId(id);
        user.setPassword(password);
        user.setUsername(name);
        user.setSex(sex);
        user.setTel(tel);
        Userservices userserices=new Userservices();
        user=userserices.CheckLogin(user);
        if(Objects.isNull(user)){
            if(Objects.isNull(password)||Objects.isNull(configpassword)){
                msg="密码为空";
            }
            else if(password.equals(configpassword)){
                user=new User();
                user.setId(id);
                user.setPassword(password);
                user.setSex(sex);
                user.setUsername(name);
                user.setTel(tel);
                if(userserices.SaveUser(user)){
                    req.getSession().setAttribute("user",user);
                    resp.sendRedirect("/Homepage.jsp");
                }
                else{
                    msg="服务器错误！请稍后尝试。";
                }
            }
            else{
                msg="两次密码不一致！";
            }
        }else{
            msg="用户名已被存在！";
        }
        req.setAttribute("msg",msg);
        if(msg!="")
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
    }
}
